﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MVCExtension.FrameWork;
using System.Data;

namespace MVCExtension.Authorize
{
    /// <summary>
    /// 权限过滤系统
    /// </summary>
    [ExceptionLog]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizeFilterAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            var path = filterContext.HttpContext.Request.Path.ToLower();
            if (path == "/" || path == "/Account/LogOn".ToLower() || path == "/Main/UserLogin".ToLower())
                return;//忽略对Login登录页的权限判定

            //if (!filterContext.HttpContext.User.Identity.IsAuthenticated)//如果没有登录
            //{
            //    filterContext.Result = new HttpUnauthorizedResult();//直接URL输入的页面地址跳转到登陆页
            //}



            //object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ViewPageAttribute), true);
            //var isViewPage = attrs.Length == 1;//当前Action请求是否为具体的功能页

            //if (!isViewPage)
            //{

            //    if (this.AuthorizeCore(filterContext) == false)//根据验证判断进行处理
            //    {

            //        Logger.Debug("验证失败，没有权限！");
            //        filterContext.Result = new ContentResult { Content = @"alert('抱歉,你不具有当前操作的权限！')" };//功能权限弹出提示框

            //    }
            //}
            if (this.AuthorizeCore(filterContext) == false)//根据验证判断进行处理
            {

                Logger.Debug("验证失败，没有权限！");
                filterContext.Result = new ContentResult { Content = @"alert('抱歉,你不具有当前操作的权限！')" };//功能权限弹出提示框

            }
        }
        //权限判断业务逻辑
        protected virtual bool AuthorizeCore(ActionExecutingContext filterContext)
        {


            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();


            //多线程异步记录访问日志。
            System.Threading.ThreadPool.QueueUserWorkItem(
                new System.Threading.WaitCallback(
                    LogUserAction), filterContext);            //对用户访问进行日志记录

            //if (!LogOnAction.CheckUserPower(controllerName, actionName))
            //{
            //    return false;
            //}

            return true;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="controllerName"></param>
        /// <param name="actionName"></param>
        protected void LogUserAction(object filterContexts)
        {
            ActionExecutingContext filterContext = (ActionExecutingContext)filterContexts;
            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();

            string sfromat = @"INSERT INTO[UserOperation_log]
           ([UserDepartmentID]
           ,[UserNikeName]
           ,[UserOperation]
           ,[OperationIP]
           ,[OperationDate],[Controller],[action])
     VALUES
           ('{0}'
           ,'{1}'
           ,'{2}'
           ,'{3}'
           ,'{4}','{5}','{6}')";
            string Args = GetAllIds(filterContext);
            string sql = string.Format(sfromat, MasterHelper.UserDepartmentID, MasterHelper.NickName, Args, MasterHelper.LoginIP, StringHelper.getFormatdDateTime(DateTime.Now), controllerName, actionName);
             Logger.Debug(sql);
            DBHelper.ExecuteSql(sql);
        }



        
        /// <summary>
        /// 获取参数信息
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private string GetAllIds(ActionExecutingContext filterContext)
        {

            System.Web.HttpRequestBase httpRequestBase = filterContext.RequestContext.HttpContext.Request;

            string tmp = string.Empty;


            tmp += httpRequestBase.HttpMethod+" " + httpRequestBase.Url.PathAndQuery;
            for (int i = 0; i < httpRequestBase.Form.Count; i++)
            {
                tmp += httpRequestBase.Form[i].ToString() + ",";
            }
            return tmp;
        }
    }
}
